<@>layout("/common/default.html"){
<script type="text/javascript" src="${ctxPath}/static/jim/date.js"></script>
<style type="text/css" media="screen">
    * {
        margin: 0;
        padding: 0;
    }

    #wrap {
        margin: 10px auto;
        width: 80%;
        height: 99%;
    }

    .unit {
        border-radius: 5px;
        margin-bottom: 5px;
        padding: 5px;
        border: solid 1px #BABABA;
        height: auto;
        clear: both;
        box-sizing: border-box;
    }

    .unit label {
        text-align: right;
        width: 100px;
        line-height: 30px;
        display: inline-block;
    }

    .unit input {
        line-height: 30px;
        width: 100px;
        height: 30px;
    }

    .log {
        font-size: 11px;
        font-family: Courier;
        overflow: auto;
        height: 100%;
        background: white;
        width: 85%;
        float: left
    }

    .log p {
        padding: 2px;
        margin: 0;
    }

    .content {
        width: 100%;
        overflow: hidden;
        height: 80%;
        margin: 0 0 5px 0;
    }

    .online {
        margin-left: -1px;
        border-radius: 5px;
        width: 15%;
        height: 100%;
        float: right;
        background: #FCFCFC;
        border: solid 1px #bababa;
        box-sizing: border-box;
    }

    .layui-btn + .layui-btn {
        margin-left: 0px;
    }
</style>
</div>
<div class="x-body">
</div>
<div id="wrap" style="height:600px;">
    <div class="content">
        <div id="logs" class="unit log"></div>
        <div id="onlinePanel" class="online">
            &nbsp;在线成员(0/0)
        </div>
    </div>
    <div class="unit">
        <label>输入内容:</label>
        <input id="content" style="width:500px;" onkeydown="keyDown(event)"/>&nbsp;

        <button class="layui-btn layui-btn-sm layui-btn-normal" title="发送" onclick="sendGroup()">
            <i class="layui-icon">&#xe609;</i>
        </button>&nbsp;

        <button class="layui-btn layui-btn-sm layui-btn-normal" id="uploadImg">
            <i class="layui-icon">&#xe67c;</i>
        </button>&nbsp;

        <button class="layui-btn layui-btn-sm layui-btn-danger" title="清空" onclick="clearLogs()">
            <i class="layui-icon">&#xe640;</i>
        </button>&nbsp;

        <button class="layui-btn layui-btn-sm layui-btn-danger" title="关闭聊天室" onclick="disConnect()">
            <i class="layui-icon">&#x1006;</i>
        </button>&nbsp;
        <input id="join_group_id" value="${number}" style="width:100px; display: none" placeholder="输入群组ID"/>
        <input id="history_group_id" style="width:100px; display: none" value="${number}" placeholder="输入群组ID"/>
        <a href="http://leonlimstest.oss-cn-beijing.aliyuncs.com/static/files/emailFile/0666/d3dc7c15fe3341c2a8abad43ef2deda7.exe">文件下载</a>
    </div>
</div>
<script>
    var socket;
    var logDiv;
    var username = '${userName}';
    var password = '${number}';
    var gropWtdbh = '${number}';
    var name = '${name}';
    var userId = '${userId}';
    var group_id = '${group_id}'
    var onSelected;
    var curUser;
    var ip = '${serviceIp}';
    var port = '${port}';
    var groups = [];
    var ryImgSrc = "${ctxPath}/static/im/images/user.png";
    var saveGroupOfflineMessage = false;//保存群组信息
    $(function () {
        socketConnect();//socket连接
        initUpload();//初始化layui上传按钮
        scrollToBottomImg();//光标显示最底部
    });

    function initUpload() {
        var Imgentity = {};// 传输数据的实体变量
        Imgentity.number = gropWtdbh;
        layui.use('upload', function () {
            var upload = layui.upload;
            var imgUrl = "${ctxPath}/ajax/layim/uploadImg";
            //执行实例
            var uploadInst = upload.render({
                elem: '#uploadImg' //绑定元素
                , url: imgUrl //上传接口
                , method: 'POST'
                , accept: 'images'
                , data: Imgentity
                , async: false
                , done: function (r) {
                    //上传完毕回调
                    var code = r.code;
                    var msg = r.msg;
                    //假设code=0代表上传成功
                    if (code == '0') {
                        var imgUrl = r.data.src;
                        sendUploadImg(imgUrl);
                    } else {
                        $.msg(msg, function () {
                        }, 2);
                    }
                }
                , error: function () {
                }
            });
        });

    }

    //显示图片100%大小
    function showImg(obj) {
        var imgUrl = $(obj).attr('url');
        //弹出即全屏
        var index = layer.open({
            type: 2,
            content: '${ctxPath}/layim/orders/showImg?imgUrl=' + imgUrl,
            area: ['500px', '710px'],
            maxmin: true
        });
        layer.full(index);
    }

    function sendUploadImg(imgUrl) {
        var createTime = new Date().getTime();
        if (imgUrl == "")
            return;
        var msg = "{\"from\": \"" + userId + "\",\"createTime\":" + createTime + ",\"cmd\":11,\"group_id\": \"" + group_id + "\",\"chatType\":\"1\",\"msgType\":\"1\",\"content\": \"" + imgUrl + "%" + name + "\"}";
        socket.send(msg);
        var chatObj = eval("(" + msg + ")");
        var createTime = new Date(chatObj.createTime).Format("yyyy/MM/dd HH:mm:ss");
        //处理数据
        logDiv.innerHTML += "<span style='color: #228B22' size='1' style='font-weight: bold'>" + curUser.nick + "" + " " + createTime + "</span><br>";
        //处理数据
        var currentImgUrl = "${ctxPath}/orders/getImg?key=" + imgUrl;
        logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;<img width='200' onclick='showImg(this)' url ='" + imgUrl + "' src='" + imgUrl + "'></span><br>";
        document.getElementById('content').value = "";
        scrollToBottomImg();
    }

    function socketConnect() {
        logDiv = document.getElementById('logs');
        // socket创建对象
        socket = new WebSocket("ws:" + ip + ":" + port + "?username=" + username + "&password=" + password);
        // 和服务器建立连接,发送登陆Jim命令
        socket.onopen = function (e) {
            logDiv.innerHTML += "<span style='color: green'  size='1'>登录成功...</span><br>";
            var userCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\"" + userId + "\"}";
            var msgCmd = "{\"cmd\":19,\"type\":\"0\",\"userId\":\"" + userId + "\"}";
            socket.send(userCmd);//获取登录用户信息;
            socket.send(msgCmd);//获取用户离线消息(好友+群组);
            scrollToBottom();
        };
        //连接失败
        socket.onerror = function (e) {
            logDiv.innerHTML += "<span style='color: red'  size='1'>异常:" + e + "</span><br>";
            scrollToBottom();
        };
        //关闭连接退出登陆
        socket.onclose = function (e) {
            curUser = null;
            logDiv.innerHTML += "<span style='color: green' size='1'>退出登录...</span><br>";
            document.getElementById("onlinePanel").innerHTML = "&nbsp;在线成员(0/0)";
            scrollToBottom();
        };
        //监听服务器的信息
        socket.onmessage = function (e) {
            var data = e.data;
            var dataObj = eval("(" + data + ")");//转换为json对象
            //console.log("监听数据内容"+JSON.stringify(dataObj))
            if (dataObj.command == 11) {//接收到聊天响应处理;
                COMMAND_CHAT_RESP(dataObj);
            } else if (dataObj.command == 18) {//获取用户信息响应处理;
                COMMAND_GET_USER_RESP(dataObj);
            } else if (10000 == dataObj.code && dataObj.command == 12) {//聊天发送状态;
                COMMAND_CHAT_RESP_SEND_STATUS(data);
            } else if (dataObj.command == 9) {//加入群组的消息通知处理;
                COMMAND_JOIN_GROUP_NOTIFY_RESP(dataObj);
                scrollToBottom();
            } else if (dataObj.command == 10) {
                COMMAND_EXIT_GROUP_NOTIFY_RESP(dataObj);//退出聊天室
                scrollToBottom();
            } else if (dataObj.command == 20 && dataObj.code == 10016) {//处理离线消息;
                var msgFlag = "离线消息";
                COMMAND_GET_MESSAGE_RESP(dataObj, msgFlag);
                scrollToBottom();
            } else if (dataObj.command == 20 && dataObj.code == 10018) {//处理历史消息;
                var msgFlag = "历史消息";
                var msgObj = dataObj.data;
                if (msgObj) {
                    COMMAND_GET_MESSAGE_RESP(dataObj, msgFlag);//处理用户同步+持久化消息
                } else {//没有历史消息;
                    // OTHER(data);
                }
            } else {
                //OTHER(data);
            }
            //  scrollToBottom();
        };
    }

    //退出聊天室
    function COMMAND_EXIT_GROUP_NOTIFY_RESP(data) {
        var exitGroupNotify = data.data;
        console.log("监听退出信息" + JSON.stringify(data))
        var onlineUserCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\"" + userId + "\"}";
        logDiv.innerHTML += "<span style='color: #A3A3A3' size='1'>" + exitGroupNotify.user.nick + "退出群聊...</span><br>";
        socket.send(onlineUserCmd);//获取在线用户列表;
        saveGroupOfflineMessage = true;
        groupHistoryCmd();
    }

    //加入群组的消息通知处理;
    function COMMAND_JOIN_GROUP_NOTIFY_RESP(data) {
        var joinGroupNotify = data.data;
        if (curUser) {
            logDiv.innerHTML += "<span style='color: #A3A3A3' size='1'>" + joinGroupNotify.user.nick + "加入群聊...</span><br>";
            var onlineUserCmd = "{\"cmd\":17,\"type\":\"0\",\"userid\":\"" + userId + "\"}";
            socket.send(onlineUserCmd);//获取在线用户列表;
        }
    }

    //加入群组响应状态处理;
    function COMMAND_JOIN_GROUP_RESP(data) {
        //成功加入群组响应信息;
    }

    //发送聊天请求发送状态处理;
    function COMMAND_CHAT_RESP_SEND_STATUS(data) {
        //发送成功后的状态处理...
        console.log("聊天室监听发送信息数据" + JSON.stringify(data))
    }

    //获取用户信息响应处理;
    var index = 0;

    function COMMAND_GET_USER_RESP(data) {
        var user = data.data;
        console.log("获取人员信息------》》》》" + JSON.stringify(data))
        console.log("获取人员" + user);
        curUser = user;
        if (0 == index) {
            groupHistoryCmd();
        }
        index++;
        initOnlineUsers();
    }

    //接收到聊天响应处理;
    function COMMAND_CHAT_RESP(data) {
        var chatObj = data.data;
        var createTime = new Date(chatObj.createTime).Format("yyyy/MM/dd HH:mm:ss");
        var from = chatObj.from;
        if (from == userId)
            return;
        var content = chatObj.content.split('%')[0];
        var receiveName = chatObj.content.split('%')[1];
        var user = getOnlineUserById(from);
        var msgType = chatObj.msgType;//0 文字， 1图片
        if (user) {
            logDiv.innerHTML += "<span style='color: #009ACD'  size='1' style='font-weight: bold'>" + receiveName + " " + createTime + "</span><br>";
        } else {
            logDiv.innerHTML += "<span style='color: #009ACD' size='1' style='font-weight: bold'>" + receiveName + " " + createTime + "</span><br>";
        }
        if ("0" == msgType) {
            logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;" + content + "</span><br>";
            scrollToBottom();
        } else if ("1" == msgType) {
            var currentImgUrl = "${ctxPath}/orders/getImg?key=" + content;
            console.log("接收信息" + currentImgUrl);
            logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;<img width='200' onclick='showImg(this)' url ='" + content + "' src='" + content + "'></span><br>";
            scrollToBottomImg();
        } else if ("2" == msgType) {
            logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;<video width='320' height='240' controls='controls'><source src='" + content + "'/></video></span><br>";
            scrollToBottomImg();
        } else if ("3" == msgType) {
            logDiv.innerHTML += "<span style='color: black' size='1'><a  href='" + content + "' download='' target='_blank'><i class='layui-icon '></i><cite>下载文件</cite></a></span><br>";
            scrollToBottomImg();
        }

    }

    //处理用户同步+持久化消息
    function COMMAND_GET_MESSAGE_RESP(data, msgFlag) {
        var msgObj = data.data;
        friendOfflineMessage(msgObj, msgFlag);
        groupOfflineMessage(msgObj, msgFlag);
    }

    //好友消息
    function friendOfflineMessage(msgObj, msgFlag) {
        var friends = msgObj.friends;
        for (var key in friends) {
            var chatDatas = friends[key];
            for (var index in chatDatas) {
                var user_id = chatDatas[index].from;
                var createTime = new Date(chatDatas[index].createTime).Format("yyyy/MM/dd HH:mm:ss");
                logDiv.innerHTML += "<span style='color:#009ACD' size='1' style='font-weight: bold'>" + user_id + "</span><span style='color: #DC143C' size='1' style='font-weight: bold'>(好友" + msgFlag + ")</span>" + "<span style='color: #009ACD' size='1' style='font-weight: bold'>" + createTime + "</span><br>";
                logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;" + chatDatas[index].content + "</span><br>";
            }
        }
    }

    //发送ajax保存历史群聊信息
    function saveGroupMessage(content) {
        console.log(gropWtdbh);
        console.log(groups);
        $.cajax('${ctxPath}/ajax/orders/saveGroupMessage', {
            'number': gropWtdbh,
            'content': content
        }, function (r) {
            var code = r.code;
            var msg = r.msg;
            socket.close();
            window.location.href = '${ctxPath}/orders/list';
        })
    }

    //群组消息
    function groupOfflineMessage(msgObj, msgFlag) {
        var groups = msgObj.groups;
        if (false == saveGroupOfflineMessage) {
            for (var key in groups) {
                var chatDatas = groups[key];
                for (var index in chatDatas) {
                    var content = chatDatas[index].content.split("%")[0];
                    var userName = chatDatas[index].content.split("%")[1];
                    //msgType 0文字 1 图片
                    var msgType = chatDatas[index].msgType;
                    var createTime = new Date(chatDatas[index].createTime).Format("yyyy/MM/dd HH:mm:ss");
                    logDiv.innerHTML += "<span style='color:#009ACD' size='1' style='font-weight: bold'>" + userName + "</span><span style='color: #DC143C' size='1' style='font-weight: bold'>(群聊[" + chatDatas[index].group_id + "]" + msgFlag + ")</span>" + "<span style='color: #009ACD' size='1' style='font-weight: bold'>" + createTime + "</span><br>";
                    if ("0" == msgType) {
                        logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;" + content + "</span><br>";
                        scrollToBottom();
                    } else if ("1" == msgType) {
                        logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;<img width='200' onclick='showImg(this)' url = '" + content + "' src='" + content + "'></span><br>";
                        scrollToBottomImg();
                    } else if ("2" == msgType) {
                        logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;<video width='320' height='240' controls='controls'><source src='" + content + "'/></video></span><br>";
                        scrollToBottomImg();
                    } else if ("3" == msgType) {
                        logDiv.innerHTML += "<span style='color: black' size='1'><a  href='" + content + "' download='' target='_blank'><i class='layui-icon '></i><cite>下载文件</cite></a></span><br>";
                        scrollToBottomImg();
                    }

                }
            }
        } else {
            //发送ajax保存历史群聊信息
            var content = [];
            for (var key in groups) {
                var chatDatas = groups[key];
                for (var index in chatDatas) {
                    var user_id = chatDatas[index].from;
                    var createTime = new Date(chatDatas[index].createTime).Format("yyyy/MM/dd HH:mm:ss");
                    var oneText = {
                        user_id: user_id,
                        createTime: createTime,
                        content: chatDatas[index].content,
                    }
                    content.push(oneText);
                }
            }
            saveGroupMessage(JSON.stringify(content));
        }
    }

    //其它信息处理;
    function OTHER(data) {
        //处理数据
        logDiv.innerHTML += "<span style='color: green' size='1'>" + data + "</span><br>";
    }

    function getOnlineUserById(id) {
        var groups = curUser.groups;
        var onlineUserStr = "";
        for (var g = 0; g < groups.length; g++) {
            var group = groups[g];
            var users = group.users;
            for (var u = 0; u < users.length; u++) {
                var user = users[u];
                if (user.nick == id) {
                    return user;
                }
            }
        }
    }

    function initOnlineUsers() {
        console.log(curUser);
        var groups = curUser.groups;
        if (groups) {
            var onlineUserStr = "";
            for (var g = 0; g < groups.length; g++) {
                var group = groups[g];
                var users = group.users;
                if (gropWtdbh == group.name) {
                    onlineUserStr += "&nbsp;" + group.name + "在线成员(" + users.length + "/" + users.length + ")";
                    for (var u = 0; u < users.length; u++) {
                        var user = users[u];
                        onlineUserStr += "<div id=\"" + user.nick + "\" nick=\"" + user.nick + "\" style=\"line-height: 25px;margin: 5px 5px 0 5px;padding-left:15px;cursor:pointer;\" onclick=\"onlineDb(this);\" onmouseover=\"onlineMove(this);\"  onmouseleave=\"onlineLeave(this);\"><img alt=\"" + user.nick + "\" src=\"" + ryImgSrc + "\" height=\"25px\" width=\"25px;\" style=\"float:left\">&nbsp;<span size='2'>" + user.nick + "</span></div>";
                    }
                }
            }
            if (!onlineUserStr) {
                onlineUserStr = "&nbsp;在线成员(0/0)";
            }
            document.getElementById("onlinePanel").innerHTML = onlineUserStr;
        }
    }

    //退出之前保存或者更新聊天内容到数据库
    function disConnect() {
        saveGroupOfflineMessage = true;
        groupHistoryCmd();
    }

    function sendGroup() {
        var createTime = new Date().getTime();
        var content = document.getElementById('content').value;
        if (content == "")
            return;
        var msg = "{\"from\": \"" + userId + "\",\"createTime\":" + createTime + ",\"cmd\":11,\"group_id\": \"" + group_id + "\",\"chatType\":\"1\",\"msgType\":\"0\",\"content\": \"" + content + "%" + name + "\"}";
        socket.send(msg);
        var chatObj = eval("(" + msg + ")");
        var createTime = new Date(chatObj.createTime).Format("yyyy/MM/dd HH:mm:ss");
        //处理数据
        logDiv.innerHTML += "<span style='color: #228B22' size='1' style='font-weight: bold'>" + curUser.nick + "" + " " + createTime + "</span><br>";
        //处理数据
        logDiv.innerHTML += "<span style='color: black' size='1'>&nbsp;" + content + "</span><br>";
        document.getElementById('content').value = "";
        scrollToBottom();
    }

    function scrollToBottomImg() {
        setTimeout(function () {
            logDiv.scrollTop = logDiv.scrollHeight;
        }, 100)
    }

    function scrollToBottom() {
        var logDiv = document.getElementById('logs');
        logDiv.scrollTop = logDiv.scrollHeight;
    }

    function clearLogs() {
        var logDiv = $('#logs');
        logDiv.empty();
    }

    function onlineDb(obj) {
        if (onSelected) {
            if (onSelected.id != obj.id) {
                onSelected.style.background = "";
            }
        }
        obj.style.background = "#D4D4D4";
        onSelected = obj;
        var sendBtn = document.getElementById("sendBtn");
        sendBtn.style = "width: 150px;"
        sendBtn.value = "发送给:" + onSelected.id;
    }

    function onlineMove(obj) {
        if ("undefined" == typeof(onSelected) || onSelected.id != obj.id) {
            obj.style.background = "#F0F0F0";
        }
    }

    function onlineLeave(obj) {
        var onlineDiv = document.getElementById("onlinePanel").getElementsByTagName("div");
        for (var i = 0; i < onlineDiv.length; i++) {
            if ("undefined" == typeof(onSelected) || onSelected.id != onlineDiv[i].id) {
                onlineDiv[i].style.background = "";
            }
        }
    }

    function keyDown(e) {
        var ev = window.event || e;
        //13是键盘上面固定的回车键
        if (ev.keyCode == 13) {
            sendGroup();
        }
    }

    function groupHistoryCmd() {
        if (!curUser) {
            alert("请先登录!");
            return;
        }
        if (group_id == "") {
            alert("请输入要获取的群组ID!");
            return;
        }
        var msgHistoryCmd = "{\"cmd\":19,\"type\":\"1\",\"group_id\":\"" + group_id + "\",\"userId\":\"" + userId + "\"}";
        socket.send(msgHistoryCmd);//获取群组历史消息;
    }

</script>
</div>
<hr>
<@>}